<!-- 地图轨迹组件 -->
<template>
	<view>
		<cu-custom class="navBox" bgColor="bg-gradual-blue" :isBack="true">
			<block slot="backText">返回</block>
			<block slot="content">地图轨迹</block>
		</cu-custom>

		<view class="container">
			<map id='map' :latitude="latitude" :longitude="longitude" :markers="covers"
				:style="{ width: '100%', height: mapHeight + 'px' }" :scale="13" :polyline="polyline">
			</map>

			<view class="btnBox">
				<button :disabled="isDisabled" @click="start" class="cu-btn bg-blue round shadow lg">开始回放</button>
				<button @click="pause" class="cu-btn bg-red round shadow lg">暂停</button>
				<button @click="exportToPDF" class="cu-btn bg-green round shadow lg">导出PDF</button>
			</view>
		</view>
		<!-- 隐藏的Canvas用于绘制轨迹图 -->
		<canvas canvas-id="pdfCanvas"
			:style="{ position: 'absolute', left: '-9999px', top: '-9999px', width: canvasWidth + 'px', height: canvasHeight + 'px' }"></canvas>

		<!-- 加载提示 -->
		<view v-if="loading" class="loading-mask">
			<view class="loading-content">
				<view class="loading-spinner"></view>
				<text class="loading-text">{{ loadingText }}</text>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				canvasWidth: 595, // A4纸宽度(单位:pt)
				canvasHeight: 842, // A4纸高度
				dpr: 1, // 设备像素比
				loading: false,
				loadingText: "",
				tempImagePath: "",
				map: null,
				movementInterval: null, // 用于存储定时器的引用
				windowHeight: 0,
				mapHeight: 0,
				timer: null,

				isDisabled: false,
				isStart: false,
				playIndex: 1,

				id: 0, // 使用 marker点击事件 需要填写id
				title: 'map',
				latitude: 34.263734,
				longitude: 108.934843,
				// 标记点
				covers: [{
					id: 1,
					width: 42,
					height: 47,
					rotate: 270,
					latitude: 34.259428,
					longitude: 108.947040,
					iconPath: 'http://zgonline.top/car.png',
					callout: {
						content: "鄂A·88888", // <img src="车牌信息" alt="" width="50%" />
						display: "ALWAYS",
						fontWeight: "bold",
						color: "#5A7BEE", //文本颜色
						fontSize: "12px",
						bgColor: "#ffffff", //背景色
						padding: 5, //文本边缘留白
						textAlign: "center",
					},
					anchor: {
						x: 0.5,
						y: 0.5,
					},
				}],

				// 线
				polyline: [],

				// 坐标数据
				coordinate: [{
						latitude: 34.259428,
						longitude: 108.947040,
						problem: false,
					},
					{
						latitude: 34.252918,
						longitude: 108.946963,
						problem: false,
					},
					{
						latitude: 34.252408,
						longitude: 108.946240,
						problem: false,
					},
					{
						latitude: 34.249286,
						longitude: 108.946184,
						problem: false,
					},
					{
						latitude: 34.248670,
						longitude: 108.946640,
						problem: false,
					},
					{
						latitude: 34.248129,
						longitude: 108.946826,
						problem: false,
					},
					{
						latitude: 34.243537,
						longitude: 108.946816,
						problem: true,
					},
					{
						latitude: 34.243478,
						longitude: 108.939003,
						problem: true,
					},
					{
						latitude: 34.241218,
						longitude: 108.939027,
						problem: true,
					},
					{
						latitude: 34.241192,
						longitude: 108.934802,
						problem: true,
					},
					{
						latitude: 34.241182,
						longitude: 108.932235,
						problem: true,
					},
					{
						latitude: 34.247227,
						longitude: 108.932311,
						problem: true,
					},
					{
						latitude: 34.250833,
						longitude: 108.932352,
						problem: true,
					},
					{
						latitude: 34.250877,
						longitude: 108.931756,
						problem: true,
					},
					{
						latitude: 34.250944,
						longitude: 108.931576,
						problem: true,
					},
					{
						latitude: 34.250834,
						longitude: 108.929662,
						problem: true,
					},
					{
						latitude: 34.250924,
						longitude: 108.926015,
						problem: true,
					},
					{
						latitude: 34.250802,
						longitude: 108.910121,
						problem: true,
					},
					{
						latitude: 34.269718,
						longitude: 108.909921,
						problem: true,
					},
					{
						latitude: 34.269221,
						longitude: 108.922366,
						problem: false,
					},
					{
						latitude: 34.274531,
						longitude: 108.922388,
						problem: false,
					},
					{
						latitude: 34.276201,
						longitude: 108.923433,
						problem: false,
					},
					{
						latitude: 34.276559,
						longitude: 108.924004,
						problem: false,
					},
					{
						latitude: 34.276785,
						longitude: 108.945855,
						problem: false,
					}
				],
				posi: {
					id: 1,
					width: 32,
					height: 32,
					latitude: 0,
					longitude: 0,
					iconPath: "http://cdn.zhoukaiwen.com/car.png",
					callout: {
						content: "皖A·589545", // 车牌信息
						display: "BYCLICK",
						fontWeight: "bold",
						color: "#5A7BEE", //文本颜色
						fontSize: "12px",
						bgColor: "#ffffff", //背景色
						padding: 5, //文本边缘留白
						textAlign: "center",
					},
					anchor: {
						x: 0.5,
						y: 0.5,
					},
				}
			}
		},
		watch: {},
		// 分享小程序
		onShareAppMessage(res) {
			return {
				title: '看看这个小程序多好玩～',
			};
		},
		onReady() {
			// 创建map对象
			this.map = uni.createMapContext('map');
			// 获取屏幕高度
			uni.getSystemInfo({
				success: res => {
					this.windowHeight = res.windowHeight;
				}
			});
		},
		mounted() {
			this.setNavTop('.navBox')

			this.polyline = [{
				points: this.coordinate,
				color: '#025ADD',
				width: 4,
				dottedLine: false,
			}];
		},
		methods: {
			setNavTop(style) {
				let view = uni.createSelectorQuery().select(style);
				view
					.boundingClientRect((data) => {
						console.log("tabInList基本信息 = " + data.height);
						this.mapHeight = this.windowHeight - data.height;
						console.log(this.mapHeight);
					})
					.exec();
			},
			start() {
				if (this.movementInterval) {
					clearInterval(this.movementInterval);
				}
				this.isStart = true;
				this.moveMarker();
			},
			moveMarker() {
				if (!this.isStart) return;

				if (this.playIndex >= this.coordinate.length) {
					this.playIndex = 0;
					uni.showToast({
						title: "播放完成",
						duration: 1400,
						icon: "none",
					});
					this.isStart = false;
					this.isDisabled = false;
					return;
				}

				let datai = this.coordinate[this.playIndex];
				this.map.translateMarker({
					markerId: 1,
					autoRotate: true,
					destination: {
						longitude: datai.longitude,
						latitude: datai.latitude,
					},
					duration: 700,
					complete: () => {
						this.playIndex++;
						this.moveMarker();
					},
				});
			},
			pause() {
				this.isStart = false;
				this.isDisabled = false;
				if (this.movementInterval) {
					clearInterval(this.movementInterval);
					this.movementInterval = null;
				}
			},
			 // 修复后的导出方法
			  async exportToPDF() {
			    this.loading = true;
			    this.loadingText = "准备导出数据...";
			    
			    try {
			      // 等待Canvas绘制完成
			      await this.drawCanvas();
			      
			      // 生成图片
			      this.loadingText = "正在生成图片...";
			      const res = await new Promise((resolve, reject) => {
			        uni.canvasToTempFilePath({
			          canvasId: 'pdfCanvas',
			          quality: 1,
			          success: resolve,
			          fail: reject
			        }, this);
			      });
			      
			      this.tempImagePath = res.tempFilePath;
				  console.log('this.tempImagePath',this.tempImagePath);
			      this.sendToBackend();
			    } catch (err) {
			      console.error('导出失败:', err);
			      uni.showToast({ title: '导出失败', icon: 'none' });
			      this.loading = false;
			    }
			  },

			// 在Canvas上绘制轨迹图
			async drawCanvas() {
			    this.loadingText = "正在生成轨迹图...";
			    const ctx = uni.createCanvasContext('pdfCanvas', this);
			    
			    // 设置Canvas实际分辨率（解决高清屏模糊问题）
			    const realWidth = this.canvasWidth * this.dpr;
			    const realHeight = this.canvasHeight * this.dpr;
			    
			    // 1. 绘制白色背景（避免透明背景）
			    ctx.fillStyle = '#FFFFFF';
			    ctx.fillRect(0, 0, realWidth, realHeight);
			    
			    // 2. 应用DPI缩放
			    ctx.scale(this.dpr, this.dpr);
			    
			    // 3. 计算轨迹边界（添加10%边距）
			    const { minLat, maxLat, minLng, maxLng } = this.calculateBounds();
			    const padding = 0.1;
			    const latRange = maxLat - minLat;
			    const lngRange = maxLng - minLng;
			    
			    // 4. 计算缩放比例（考虑边距）
			    const contentWidth = this.canvasWidth * (1 - 0.3); // 70%宽度用于地图
			    const contentHeight = this.canvasHeight * 0.6;    // 60%高度用于地图
			    const scaleX = contentWidth / (lngRange * (1 + 2 * padding));
			    const scaleY = contentHeight / (latRange * (1 + 2 * padding));
			    const scale = Math.min(scaleX, scaleY);
			    
			    // 5. 坐标系转换（注意Y轴翻转）
			    const toCanvasX = lng => (lng - minLng + padding * lngRange) * scale + 0.15 * this.canvasWidth;
			    const toCanvasY = lat => this.canvasHeight * 0.7 - (lat - minLat + padding * latRange) * scale;
			    
			    // 6. 绘制轨迹线
			    ctx.beginPath();
			    this.coordinate.forEach((point, index) => {
			      const x = toCanvasX(point.longitude);
			      const y = toCanvasY(point.latitude);
			      
			      if (index === 0) ctx.moveTo(x, y);
			      else ctx.lineTo(x, y);
			    });
			    
			    ctx.strokeStyle = '#025ADD';
			    ctx.lineWidth = 3;
			    ctx.stroke();
			    
			    // 7. 绘制关键点（确保在绘制完成后调用导出）
			    return new Promise(resolve => {
			      ctx.draw(false, () => {
			        setTimeout(resolve, 300); // 确保渲染完成
			      });
			    });
			  },
			// 计算轨迹边界
			calculateBounds() {
				let minLat = this.coordinate[0].latitude;
				let maxLat = this.coordinate[0].latitude;
				let minLng = this.coordinate[0].longitude;
				let maxLng = this.coordinate[0].longitude;

				this.coordinate.forEach(point => {
					if (point.latitude < minLat) minLat = point.latitude;
					if (point.latitude > maxLat) maxLat = point.latitude;
					if (point.longitude < minLng) minLng = point.longitude;
					if (point.longitude > maxLng) maxLng = point.longitude;
				});

				return {
					minLat,
					maxLat,
					minLng,
					maxLng
				};
			},

			// 绘制点
			drawPoint(ctx, point, label, color, scale, minLat, minLng, padding, latRange, lngRange, size = 8) {
				const x = (point.longitude - minLng + padding * lngRange) * scale;
				const y = this.canvasHeight - (point.latitude - minLat + padding * latRange) * scale;

				// 绘制点
				ctx.beginPath();
				ctx.arc(x, y, size, 0, Math.PI * 2);
				ctx.fillStyle = color;
				ctx.fill();

				// 绘制标签
				ctx.fillStyle = color;
				ctx.font = 'bold 14px "Microsoft YaHei"';
				ctx.textAlign = 'center';
				ctx.fillText(label, x, y - size - 5);
			},

			// 绘制图例
			drawLegend(ctx) {
				const legendY = this.canvasHeight - 100;

				// 起点图例
				ctx.fillStyle = '#4CAF50';
				ctx.fillRect(50, legendY, 20, 20);
				ctx.fillStyle = '#333';
				ctx.font = '14px "Microsoft YaHei"';
				ctx.textAlign = 'left';
				ctx.fillText('起点', 80, legendY + 15);

				// 终点图例
				ctx.fillStyle = '#F44336';
				ctx.fillRect(150, legendY, 20, 20);
				ctx.fillText('终点', 180, legendY + 15);

				// 问题点图例
				ctx.fillStyle = '#FF9800';
				ctx.fillRect(250, legendY, 20, 20);
				ctx.fillText('问题点', 280, legendY + 15);
				
				// 轨迹图例
				ctx.strokeStyle = '#025ADD';
				ctx.lineWidth = 3;
				ctx.beginPath();
				ctx.moveTo(350, legendY + 10);
				ctx.lineTo(380, legendY + 10);
				ctx.stroke();
				ctx.fillText('轨迹线', 400, legendY + 15);
			},

			// Canvas转为图片
			canvasToImage() {
				this.loadingText = "正在生成图片...";
				uni.canvasToTempFilePath({
					canvasId: 'pdfCanvas',
					quality: 1,
					success: (res) => {
						console.log('res', res);
						this.tempImagePath = res.tempFilePath;
						this.loadingText = "正在生成PDF文件...";
						// this.sendToBackend();
					},
					fail: (err) => {
						console.error('Canvas转图片失败', err);
						this.loading = false;
						uni.showToast({
							title: '图片生成失败',
							icon: 'none'
						});
					}
				}, this);
			},
			// 发送到后端生成PDF
			// 发送到后端生成PDF
			sendToBackend() {
				// 这里需要替换为您的后端API地址
				const apiUrl = 'http://localhost:3000/api/generate-pdf';

				uni.uploadFile({
					url: apiUrl,
					filePath: this.tempImagePath,
					name: 'routeImage',
					formData: {
						points: JSON.stringify(this.coordinate),
					},
					success: (uploadRes) => {
						console.log('uploadRes', uploadRes);

						// 1. 检查状态码 - 200表示成功
						if (uploadRes.statusCode === 200) {
							// 2. 直接处理二进制PDF数据
							const pdfData = uploadRes.data;

							// 3. 保存PDF到本地文件系统
							const filePath = `${wx.env.USER_DATA_PATH}/generated.pdf`;

							uni.getFileSystemManager().writeFile({
								filePath: filePath,
								data: pdfData,
								encoding: 'binary', // 关键：指定二进制格式
								success: () => {
									// 4. 打开保存的PDF文件
									uni.openDocument({
										filePath: filePath,
										fileType: 'pdf',
										success: () => {
											console.log('打开PDF成功');
											this.loading = false;
										},
										fail: (err) => {
											console.error('打开PDF失败:', err);
											uni.showToast({
												title: '打开PDF失败',
												icon: 'none'
											});
											this.loading = false;
										}
									});
								},
								fail: (writeErr) => {
									console.error('保存PDF失败:', writeErr);
									uni.showToast({
										title: '保存PDF失败',
										icon: 'none'
									});
									this.loading = false;
								}
							});
						} else {
							// 处理非200状态码
							this.loading = false;
							uni.showToast({
								title: `服务器错误: ${uploadRes.statusCode}`,
								icon: 'none'
							});
						}
					},
					fail: (err) => {
						console.error('上传失败:', err);
						this.loading = false;
						uni.showToast({
							title: '上传图片失败',
							icon: 'none'
						});
					}
				});
			},

			// // 下载PDF
			// downloadPDF(tempFilePath) {
			// 	this.loadingText = "正在下载PDF文件...";

			// 	// 直接打开文档（因为Koa2返回的是PDF文件流）
			// 	uni.openDocument({
			// 		filePath: tempFilePath,
			// 		fileType: 'pdf',
			// 		showMenu: true,
			// 		success: () => {
			// 			this.loading = false;
			// 			uni.showToast({
			// 				title: 'PDF打开成功',
			// 				icon: 'success'
			// 			});
			// 		},
			// 		fail: (err) => {
			// 			console.error('打开PDF失败:', err);
			// 			this.loading = false;
			// 			uni.showToast({
			// 				title: '打开PDF失败',
			// 				icon: 'none'
			// 			});
			// 		}
			// 	});
			// }

		}
	}
</script>

<style lang="scss" scoped>
	.container {
		position: relative;
	}

	.btnBox {
		width: 750rpx;
		position: absolute;
		bottom: 60rpx;
		z-index: 99;
		display: flex;
		justify-content: space-around;
	}
</style>